from odoo.http import request, Response
import functools
import json


def check_token(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        # 00 处理参数
        result = {
            'json': True,
            'data': {}
        }
        api_result = {
            "code": 0,
            "message": "success",
            "data": {
                "total": 0,
                "list": []
            }
        }
        data = request.httprequest.get_json()
        token = data.get('token', False)
        # 01 如果token值为空
        if not token:
            api_result['code'] = -1
            api_result['message'] = "Token值不可为空"
            result['data'] = api_result
            return Response(json.dumps(result, ensure_ascii=False))
        # 02 token值不为空,则进行检验
        else:
            # 02.1 检验token过期或失效的情况
            api_user_obj = request.env['api.users'].sudo().search([('token', '=', token)], limit=1)
            # 02.1.1 检验token过期的情况
            if api_user_obj and api_user_obj.id:
                if token == api_user_obj.sudo().get_token():
                    pass
                else:
                    api_result['code'] = -1
                    api_result['message'] = "Token值过期或失效"
                    result['data'] = api_result
                    return Response(json.dumps(result, ensure_ascii=False))
            # 02.1.2 检验token失效的情况
            else:
                api_result['code'] = -1
                api_result['message'] = "Token值过期或失效"
                result['data'] = api_result
                return Response(json.dumps(result, ensure_ascii=False))

            # 02.2 检查该用户是否有权限访问接口
            api_user_route_list = [r.route_url for r in api_user_obj.api_user_route_ids]
            is_user_can_access = False
            for route_url in api_user_route_list:
                if route_url in request.httprequest.base_url:
                    is_user_can_access = True
            if not is_user_can_access:
                api_result['code'] = -1
                api_result['message'] = "当前用户没有访问此接口的权限"
                result['data'] = api_result
                return Response(json.dumps(result, ensure_ascii=False))

            # 02.3 todo　日志记录
            # pass
        return func(*args, **kwargs)
    return decorator

